package com.powernode.listener;

import com.rabbitmq.client.Channel;
import org.redisson.api.RBloomFilter;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: powernode
 */
@Component
public class MsgListener {


    @Autowired
    private RBloomFilter<String> bloomFilter;

    @RabbitListener(queues = "test.queue")
    public void handleMsg(Message message, Channel channel) {
        String msg = new String(message.getBody());
        String messageId = message.getMessageProperties().getMessageId();
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 判断是否存在
        if (bloomFilter.contains(messageId)) {
            System.out.println("这个消息存在过，也可能是误判，需要额外处理：" + msg);
            try {
                channel.basicAck(deliveryTag, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        // 做业务操作
        System.out.println("做业务操作");
        // 存放过滤器
        bloomFilter.add(messageId);
        try {
            channel.basicAck(deliveryTag, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
